package org.helgoboss.janana_tray_resource_management

import org.osgi.service.obr.Resource
import org.osgi.framework.Bundle

class BundleResource {

    sealed abstract class State(val displayName: String)

    object NotInstalled extends State("Not installed")
    object Uninstalled extends State("Uninstalled")
    object Installed extends State("Installed")
    object Resolved extends State("Resolved")
    object Starting extends State("Starting")
    object Stopping extends State("Stopping")
    object Active extends State("Active")


    var resource: Option[Resource] = None
    var bundle: Option[Bundle] = None
    
    def symbolicName = {
        resource match {
            case Some(resource) => resource.getSymbolicName
            case None => bundle.get.getSymbolicName
        }
    }
    
    def version = {
        resource match {
            case Some(resource) => resource.getVersion
            case None => bundle.get.getVersion
        }
    }
    
    def categories: Seq[String] = {
        resource match {
            case Some(resource) => resource.getCategories
            case None => 
                val categoriesString = bundle.get.getHeaders.get("Bundle-Category").asInstanceOf[String]
                if (categoriesString == null) {
                    Nil
                } else {
                    categoriesString.split(",").map(_.trim)
                }
        }
    }
    
    def presentationName = {
        resource match {
            case Some(resource) => resource.getPresentationName
            case None => 
                val bundleName = bundle.get.getHeaders.get("Bundle-Name").asInstanceOf[String]
                if (bundleName == null) {
                    ""
                } else {
                    bundleName
                }
        }
    }
    
    def state = {
        import Bundle._
        bundle match {
            case Some(bundle) =>
                bundle.getState match {
                    case UNINSTALLED => Uninstalled
                    case INSTALLED => Installed
                    case RESOLVED => Resolved
                    case STARTING => Starting
                    case STOPPING => Stopping
                    case ACTIVE => Active
                }
                
            case None => NotInstalled
        }
    }
    
    def isInstalled = {
        state != Uninstalled && state != NotInstalled
    }
    
    override def equals(o: Any) = {
        if (o.isInstanceOf[BundleResource]) {
            val br2 = o.asInstanceOf[BundleResource]
            symbolicName == br2.symbolicName && version == br2.version
        } else {
            false
        }
    }
    
    // TODO hashCode
}